<template>
    <div class="modal">
        <!-- 遮罩 -->
        <div class="mask" @click="changeIsShowLoginModal(false)"></div>
        <!-- 登录框 -->
        <div class="login">
            <div class="close" @click="changeIsShowLoginModal(false)"></div>
            <section class="nav">
                <a href="#" :class="{active:isShowContent}" @click="isShowContent=true">手机号码登录</a> |
                <a href="#" :class="{active:!isShowContent}" @click="weixinClick">微信二维码登录</a>
                <!-- weixinClick -->
            </section>
            <div class="content">
                <div class="phoneLogin" v-show="isShowContent">
                    <div class="row">
                        <input type="text" placeholder="请输入手机号" class="ipt" v-model.trim="phoneNum" />
                    </div>
                    <div class="row">
                        <slide-verify
                            :l="42"
                            :r="20"
                            :w="362"
                            :h="140"
                            @success="onSuccess"
                            @fail="onFail"
                            @refresh="onRefresh"
                            :style="{ width: '100%' }"
                            class="slide-box"
                            ref="slideBlock"
                            :slider-text="msg"
                            :imgs="arr"
                            :accuracy="20"
                        ></slide-verify>
                    </div>
                    <div class="row">
                        <input
                            type="text"
                            placeholder="请输入短信验证码"
                            class="ipt"
                            v-model.trim="verifyCode"
                        />
                        <button class="btn btncode">
                            <span v-show="!isShowGetCode" @click="getCode">获取验证码</span>
                            <span v-show="isShowGetCode">{{count}}S</span>
                        </button>
                    </div>
                    <div class="row">
                        <button class="btn btnlogin" @click="login">登录</button>
                    </div>
                </div>
                <div class="qrlogin" v-show="!isShowContent">
                    <div id="weixin" class="qrcode" v-show="!isShowForm">二维码</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import { validatePhoneNumber } from "@/utils/index";
import {
    sendSMSApi,
    phoneReginApi,
    weixinBindingApi,
    userProfilesApi,
} from "@/request/api";
export default {
    data() {
        return {
            // 微信二维码登录和手机号码登录
            isShowContent: true,
            msg: "向右滑动",
            // 滑块本地图片
            arr: [
                require("../assets/img/integral-01.9386d4bf.png"),
                require("../assets/img/integral-02.150d92a1.png"),
                require("../assets/img/integral-03.9870f3f1.png"),
                require("../assets/img/integral-04.afadcbdf.png"),
            ],
            // 用户输入手机号码
            phoneNum: "",
            // 倒计时最大时间
            count: 5,
            // 是否显示倒计时
            isShowGetCode: false,
            // 用户输入的验证码
            verifyCode: "",
            isShowForm: false,
        };
    },
    computed: {
        ...mapState({
            isShowLoginModal: (state) => state.hdIsShowModal.isShowLoginModal,
        }),
    },
    methods: {
        weixinClick() {
            // 点击切换微信扫码登录这一项，并向微信扫码登录
            this.isShowForm = false;
            this.isShowContent = false;
            // 微信登录第一步：申请微信登录二维码
            let _this = this;
            new WxLogin({
                id: "weixin",
                appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
                scope: "snsapi_login",
                // 扫码成功后重定向的接口
                redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
                // state填写编码后的url
                state: encodeURIComponent(
                    window.btoa("http://127.0.0.1:8080" + _this.$route.path)
                ),
                // 调用样式文件
                href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0KLmltcG93ZXJCb3ggcXJjb2RlIHsNCiAgbWFyZ2luLXRvcDogMjBweDsNCiAgdGV4dC1hbGlnbjogY2VudGVyOw0KfQ0",
            });
        },
        ...mapMutations({
            changeIsShowLoginModal: "hdIsShowModal/changeIsShowLoginModal",
            changeIsLogined: "loginStatus/changeIsLogined",
            changeIsShowToast: "showToast/changeIsShowToast",
        }),
        ...mapActions({
            asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
            asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
        }),

        // 拼图成功
        onSuccess(times) {
            let ms = (times / 1000).toFixed(1);
            this.msg = "login success, 耗时 " + ms + "s";
        },
        // 拼图失败
        onFail() {
            this.onRefresh(); // 重新刷新拼图
        },
        // 拼图刷新
        onRefresh() {
            this.msg = "再试一次";
        },
        // 封装倒计时
        countDown() {
            let timer = null;
            timer = setInterval(() => {
                this.count--;
                if (this.count == 0) {
                    // 清除定时器
                    clearInterval(timer);
                    // 恢复倒计时最大值
                    this.count = 5;
                    // 隐藏倒计时显示获取验证码
                    this.isShowGetCode = false;
                }
            }, 1000);
        },
        toVerify() {
            // 验证手机号码是否合法
            // 验证已提取到utils
            if (!validatePhoneNumber(this.phoneNum)) {
                // alert("请输入正确的手机号码");
                this.asyncChangeIsShowToast({
                    isShow: true,
                    title: "请输入正确的手机号码",
                    type: "danger",
                });
                return;
            }
            // 验证滑块是否正确;
            if (this.msg == "再试一次" || this.msg == "向右滑动") {
                this.asyncChangeIsShowToast({
                    isShow: true,
                    title: "请滑到指定位置",
                    type: "danger",
                });
                return;
            }
            return true;
        },
        // 获取验证码
        async getCode() {
            //
            let flag = this.toVerify();
            if (!flag) return; // 如果验证不通过 return
            // 发起请求获取验证码
            let res = await sendSMSApi({
                phone: this.phoneNum,
            });
            if (!res) return;
            console.log(res);

            if (res.code == 0) {
                alert(res.message);
                /// !
                // 显示倒计时
                this.isShowGetCode = true;
                // 调用倒计时函数
                this.countDown();
            }
        },
        async login() {
            // 1.验证手机号码,不成功
            // 2.验证滑块验证码
            if (!this.toVerify()) return;
            // 3.验证手机验证码
            if (this.verifyCode == "") {
                this.asyncChangeIsShowToast({
                    isShow: true,
                    title: "请输入验证码",
                    type: "warning",
                });
                return;
            }
            // 4.发起登录请求
            let uuid = localStorage.getItem("uuid");
            let res = null;
            if (uuid) {
                // 有uuid 的情况
                // console.log("有uuid 的情况");
                res = await weixinBindingApi({
                    verifyCode: this.verifyCode,
                    phone: this.phoneNum,
                    uuid,
                });
            } else {
                res = await phoneReginApi({
                    verifyCode: this.verifyCode,
                    phone: this.phoneNum,
                });
            }

            if (!res) return;
            // console.log(res);
            if (res.code == 0) {
                // 1.提示成功
                // alert(res.message);
                this.asyncChangeIsShowToast({
                    isShow: true,
                    title: res.message,
                    type: "danger",
                });

                // 2.保存token
                localStorage.setItem("x-auth-token", res["x-auth-token"]);
                // 3.关闭登录框
                this.changeIsShowLoginModal(false);
                // 4.登陆状态按钮更换
                this.changeIsLogined(true);
                // let loginres = await userProfilesApi();
                // console.log(loginres);
                this.asyncChangeUserInfo();
                // 删除uuid
                localStorage.removeItem("uuid");
                // 删除地址栏中的code
                this.$router.push(this.$route.path);
            }
        },
    },
};
</script>
 
<style lang = "less" scoped>
.modal {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    .mask {
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.3);
    }
    .login {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;
        height: 423px;
        width: 555px;
        background: url("../assets/img/login-box-bg.png");
        .close {
            position: absolute;
            top: 20px;
            right: 70px;
            width: 22px;
            height: 22px;
            background: url("../assets/img/close.png");
        }
        .nav {
            display: flex;
            justify-content: center;
            font-size: 18px;
            padding-top: 50px;
            a {
                padding: 0 10px;
                color: #999;
                text-decoration: none;
                &.active {
                    color: #333;
                }
            }
        }
        .content {
            width: 350px;
            /* height: 230px; */
            margin: 20px auto;
            .phoneLogin {
                .row {
                    display: flex;
                    margin-bottom: 25px;
                }
                .ipt {
                    flex: 1;
                    height: 45px;
                    text-indent: 1em;
                    outline: none;
                }
                .btn {
                    background-color: rgb(10, 50, 142);
                    color: #fff;
                    border: none;
                }
                .btncode {
                    margin-left: 10px;
                    border-radius: 6px;
                    width: 80px;
                }
                .btnlogin {
                    width: 100%;
                    height: 50px;
                    border-radius: 6px;
                }
            }
            .qrcode {
                text-align: center;
            }
        }
    }
}

/deep/.slide-box {
    width: 100%;
    position: relative;
    box-sizing: border-box;
    canvas {
        position: absolute;
        left: 0;
        top: -120px;
        display: none;
        width: 100%;
        box-sizing: border-box;
    }
    .slide-verify-block {
        width: 85px;
        height: 136px;
    }
    .slide-verify-refresh-icon {
        top: -120px;
        display: none;
    }
    &:hover {
        canvas {
            display: block;
        }
        .slide-verify-refresh-icon {
            display: block;
        }
    }
}
</style>